package JAVAcollectionsanddatastructures.binaryTree;


import com.sun.xml.internal.ws.api.model.wsdl.WSDLOutput;

import java.util.*;

class TreeNode {
    public char value;
    public TreeNode left;
    public TreeNode right;

    public TreeNode(char value) {
        this.value = value;
    }
}

//穷举方法创建一棵二叉树
public class MybinaryTree {
    //public TreeNode root;
    public TreeNode createTree() {
        TreeNode A = new TreeNode('A');
        TreeNode B = new TreeNode('B');
        TreeNode C = new TreeNode('C');
        TreeNode D = new TreeNode('D');
        TreeNode E = new TreeNode('E');
        TreeNode F = new TreeNode('F');
        TreeNode G = new TreeNode('G');
        TreeNode H = new TreeNode('H');
        A.left = B;
        A.right = C;
        B.left = D;
        B.right = E;
        C.left = F;
        C.right = G;
        E.right = H;
        return A;//返回根节点A
    }


    //前序遍历
    public void preOrder(TreeNode root) {
        if (root == null) {
            return;
        } else {
            System.out.print(root.value + " ");
            preOrder(root.left);
            preOrder(root.right);
        }
    }

    //中序遍历
    public void inOrder(TreeNode root) {
        if (root == null) {
            return;
        } else {
            inOrder(root.left);
            System.out.print(root.value + " ");
            inOrder(root.right);
        }
    }

    //后序遍历
    public void postOrder(TreeNode root) {
        if (root == null) {
            return;
        } else {
            postOrder(root.left);
            postOrder(root.right);
            System.out.print(root.value + " ");
        }
    }

    //非递归实现方式
//    List<Character> list = new ArrayList<>();
//    public List<Character> preorderTraversal(TreeNode root) {
//        preOrder1(root, list);
//        return list;
//    }
//
//    public void preOrder1(TreeNode root, List<Character> list) {
//        if (root == null) {
//            return;
//        } else {
//            list.add(root.value);
//            preOrder1(root.left, list);
//            preOrder1(root.right, list);
//        }
//    }


    //子问题思路，例如将根节点A放到list，再将A的左树放在leftTree，右树放在rightTree
//    public List<Character> preorderTraversal(TreeNode root) {
//        List<Character> list = new ArrayList<>();
//        if (root == null) {
//            return list;
//        } else {
//            list.add(root.value);
//            List<Character> leftTree = preorderTraversal(root.left);
//            list.addAll(leftTree);
//            List<Character> rightTree = preorderTraversal(root.left);
//            list.addAll(rightTree);
//            return list;
//        }
//    }

    //2.层序遍历
    public void levelOrder(TreeNode root) {
        Queue<TreeNode> queue = new LinkedList<>();
        if (root == null) {
            return;
        }
        queue.offer(root);
        while (!queue.isEmpty()) {
            TreeNode cur = queue.poll();
            System.out.print(cur.value + " ");
            if (cur.left != null) {
                queue.offer(cur.left);
            }
            if (cur.right != null) {
                queue.offer(cur.right);
            }
        }
    }

    public List<List<Character>> levelOrder1(TreeNode root) {
        List<List<Character>> ret = new ArrayList<>();
        if (root == null) {
            return ret;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (queue.isEmpty() == false) {
            int size = queue.size();
            List<Character> list = new ArrayList<>();
            while (size != 0) {
                TreeNode cur1 = queue.poll();
                list.add(cur1.value);
                if (cur1.left != null) {
                    queue.offer(cur1.left);
                }
                if (cur1.right != null) {
                    queue.offer(cur1.right);
                }
                size--;
            }
            ret.add(list);
        }
        return ret;
    }


    // 遍历思路-求结点个数
    static int size = 0;

    int getSize1(TreeNode root) {
        if (root == null) {
            return 0;
        }
        size++;
        getSize1(root.left);
        getSize1(root.right);
        return size;
    }

    // 子问题思路-求结点个数
    int getSize2(TreeNode root) {
        if (root == null) {
            return 0;
        }
        return getSize2(root.left) + getSize2(root.right) + 1;
    }

    ;

    // 遍历思路-求叶子结点个数
    static int leafSize = 0;

    int getLeafSize1(TreeNode root) {
        if (root == null) {
            return 0;
        }
        if (root.left == null && root.right == null) {
            leafSize++;
        }
        getLeafSize1(root.left);
        getLeafSize1(root.right);
        return leafSize;
    }

    // 子问题思路-求叶子结点个数
    int getLeafSize2(TreeNode root) {
        if (root == null) {
            return 0;
        }
        if (root.left == null && root.right == null) {
            return 1;
        }
        return getLeafSize2(root.left) + getLeafSize2(root.right);
    }

    ;

    // 子问题思路-求第 k 层结点个数
    int getKLevelSize(TreeNode root, int k) {
        if (root == null) {
            return 0;
        }
        if (k == 1) {
            return 1;
        }
        return getKLevelSize(root.left, k - 1) + getKLevelSize(root.right, k - 1);
    }

    ;

    // 获取二叉树的高度
    int getHeight(TreeNode root) {
        if (root == null) {
            return 0;
        }
        //可以像下面这种方式来写，但是递归了很多次，浪费时间和空间
        //return getHeight(root.left) > getHeight(root.right) ? getHeight(root.left)+1:getHeight(root.right)+1;
        int lefttree = getHeight(root.left);
        int righttree = getHeight(root.right);
        return lefttree > righttree ? lefttree + 1 : righttree + 1;

    }

    ;

    //检测值为Value是否存在
    TreeNode find(TreeNode root, char val) {
        if (root == null) {
            return null;
        }
        if (root.value == val) {
            return root;
        }

        TreeNode left = find(root.left, val);//注意空指针异常
        if (left != null) {
            return left;
        }
        TreeNode right = find(root.right, val);
        if (right != null) {
            return right;
        }

        return null;
    }


    //判断二叉树是否为一个完全二叉树
    boolean isCompleteTree(TreeNode root) {
        if (root == null) {
            return true;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (queue.isEmpty() == false) {
            TreeNode cur = queue.poll();
            if (cur != null) {
                queue.offer(cur.left);
                queue.offer(cur.right);
            } else {
                break;
            }
        }
        while (queue.isEmpty() == false) {
            TreeNode top = queue.peek();
            if (top != null) {
                return false;
            }
            queue.poll();
        }
        return true;
    }


    //==========基础面试题=============
    //1.检查两棵二叉树是否相等
    public boolean isSameTree(TreeNode p, TreeNode q) {
        //判断根是否相等，三种情况
        if (p == null && q != null || p != null && q == null) {
            return false;
        }
        if (p == null && q == null) {
            return true;
        }
        if (p.value != q.value) {
            return false;
        }
        //p，q不为空，且pq的值相等，去判断左树是否相等，右树是否相等
        return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
    }

    //2.另一棵二叉树的子树：先判断两棵树是否相同，如果不同再去判断是否是它的左子树或右子树
    public boolean isSubtree(TreeNode root, TreeNode subRoot) {
        if (root == null || subRoot == null) {
            return false;
        }
        //判断是不是两棵相同的二叉树
        if (isSameTree(root, subRoot)) {
            return true;
        }
        //判断与它的左子树是否相同
        if (isSameTree(root.left, subRoot)) {
            return true;
        }
        //判断与它的右子树是否相同
        if (isSameTree(root.right, subRoot)) {
            return true;
        }
        return false;
    }

    //3.平衡二叉树：一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1
    //一棵树要是平衡二叉树，它的每棵子树都得是平衡二叉树
    //左右两个子树的高度差的绝对值小于等于1，且左右子树也为平衡二叉树
    public boolean isBalanced(TreeNode root) {
        if (root == null) {
            return true;
        }
        int leftHeight = getHeight(root.left);
        int rightHeight = getHeight(root.right);
        return Math.abs(leftHeight - rightHeight) <= 1 && isBalanced(root.left) && isBalanced(root.right);
    }


    //字节跳动面试题：能不能在求高度的过程中判断它是否平衡
    public int getHeight1(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int leftHeight = getHeight1(root.left);
        int rightHeight = getHeight1(root.right);

        if (leftHeight >= 0 && rightHeight >= 0 && Math.abs(leftHeight - rightHeight) <= 1) {
            return Math.max(leftHeight, rightHeight) + 1;
        } else {
            //返回了个负数，已经不平衡
            return -1;//层层向上返回-1，最后得到结果为负数的话肯定就不平衡
        }
    }

    public boolean isBalanced1(TreeNode root) {
        if (root == null) {
            return true;
        }
        return getHeight1(root) >= 0;
    }


    //4.===========对称二叉树============
    public boolean isSymmetricChild(TreeNode leftTree, TreeNode rightTree) {
        if (leftTree == null && rightTree == null) {
            return true;
        }
        if (leftTree == null || rightTree == null) {
            return false;
        }
        if (leftTree.value != rightTree.value) {
            return false;
        }
        //都不为空，且值相等，去判断
        return isSymmetricChild(leftTree.left, rightTree.right) && isSymmetricChild(leftTree.right, rightTree.left);
    }

    public boolean isSymmetric(TreeNode root) {
        if (root == null) {
            return true;
        }
        return isSymmetricChild(root.left, root.right);
    }


    //===========进阶面试题===========
    //1.找出最近公共祖先LCA
    //思路一：二叉搜索树方向：每个根的左树比它小，右树比它大，且中序遍历大小是有序的
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        //为空，没有公共祖先
        if (root == null) {
            return null;
        }
        if (root == p || root == q) {
            return root;
        }

        TreeNode leftLca = lowestCommonAncestor(root.left, p, q);
        TreeNode rightLca = lowestCommonAncestor(root.right, p, q);

        if (leftLca != null && rightLca != null) {
            return root;
        } else if (leftLca != null) {
            return leftLca;
        } else {
            return rightLca;
        }
    }

    //思路二、孩子双亲表示法，此时就变成了链表求交点问题
    //假如没有双亲节点怎么办呢？此时就可以用两个栈将根节点到指定节点的路径存储下来
    public boolean getPath(TreeNode root, TreeNode node, Stack<TreeNode> stack) {
        if (root == null || node == null) {
            return false;
        }
        stack.push(node);
        if (root == node) {
            return true;
        }
        boolean flg = getPath(root.left, node, stack);
        if (flg) {
            return true;
        }
        flg = getPath(root.right, node, stack);
        if (flg) {
            return true;
        }
        stack.pop();
        return false;
    }

    public TreeNode lowestCommonAncestor1(TreeNode root, TreeNode p, TreeNode q) {
        if (root == null) {
            return null;
        }
        Stack<TreeNode> stack1 = new Stack<>();
        getPath(root, p, stack1);
        Stack<TreeNode> stack2 = new Stack<>();
        getPath(root, q, stack2);

        int size1 = stack1.size();
        int size2 = stack2.size();
        if (size1 > size2) {
            int size = size1 - size2;
            while (size != 0) {
                stack1.pop();
                size--;
            }
            while (stack1.isEmpty() == false && stack2.isEmpty() == false) {
                if (stack1.peek() == stack2.peek()) {
                    return stack1.pop();
                } else {
                    stack1.pop();
                    stack2.pop();
                }
            }

        } else {
            int size = size2 - size1;
            while (size != 0) {
                stack2.pop();
                size--;
            }
            while (stack1.isEmpty() == false && stack2.isEmpty() == false) {
                if (stack1.peek() == stack2.peek()) {
                    return stack1.pop();
                } else {
                    stack1.pop();
                    stack2.pop();
                }
            }

        }
        return null;
    }


    // 二叉树搜索树转换成排序双向链表
    TreeNode prev = null;

    public void inorder(TreeNode pCur) {
        if (pCur == null) {
            return;
        }
        inorder(pCur.left);

        //打印
        pCur.left = prev;
        if (prev != null) {
            prev.right = pCur;
        }
        prev = pCur;
        //System.out.print(pCur.val+" ");
        inorder(pCur.right);
    }

    public TreeNode Convert(TreeNode pRootOfTree) {

        if (pRootOfTree == null) {
            return null;
        }

        inorder(pRootOfTree);

        //返回头节点
        TreeNode head = pRootOfTree;
        while (head.left != null) {
            head = head.left;
        }
        return head;
    }


    //根据前序和中序 创建一棵二叉树
    public int preIndex = 0;//前序数组的下标

    public TreeNode createTreeByPandI(int[] preorder, int[] inorder, int inbegin, int inend) {

        if (inbegin > inend) {
            //如果满足这个条件  说明 没有左树 或者 右树了
            return null;
        }
        TreeNode root = new TreeNode((char) preorder[preIndex]);
        //找到根在中序遍历的位置
        int rootIndex = findIndexOfI(inorder, inbegin, inend, preorder[preIndex]);
        if (rootIndex == -1) {
            return null;
        }
        preIndex++;
        //分别创建 左子树 和 右子树
        root.left = createTreeByPandI(preorder, inorder, inbegin, rootIndex - 1);
        root.right = createTreeByPandI(preorder, inorder, rootIndex + 1, inend);
        return root;
    }

    //key值在中序数组中的位置
    private int findIndexOfI(int[] inorder, int inbegin, int inend, int key) {

        for (int i = inbegin; i <= inend; i++) {
            if (inorder[i] == key) {
                return i;
            }
        }
        return -1;
    }

    public TreeNode buildTree(int[] preorder, int[] inorder) {
        if (preorder == null || inorder == null) {
            return null;
        }

        return createTreeByPandI(preorder, inorder, 0, inorder.length - 1);
    }


    //根据后续和中序创建一棵二叉树
   /* public int postIndex = 0;

    public TreeNode createTreeByPandI(int[] inorder, int[] postorder,int inbegin,int inend) {

        if(inbegin > inend) {
            //如果满足这个条件  说明 没有左树 或者 右树了
            return null;
        }
        TreeNode root = new TreeNode(postorder[postIndex]);
        //找到根在中序遍历的位置
        int rootIndex = findIndexOfI(inorder,inbegin,inend,postorder[postIndex]);
        if(rootIndex == -1) {
            return null;
        }
        postIndex--;
        //分别创建右子树 和  左子树
        root.right = createTreeByPandI(inorder,postorder,rootIndex+1,inend);

        root.left = createTreeByPandI(inorder,postorder,inbegin,rootIndex-1);
        return root;
    }

    private int findIndexOfI(int[] inorder,int inbegin,int inend,int key) {

        for(int i = inbegin; i <= inend;i++) {
            if(inorder[i] == key) {
                return i;
            }
        }
        return -1;
    }
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        if(postorder == null || inorder == null) return null;
        postIndex = postorder.length-1;

        return createTreeByPandI(inorder,postorder,0,inorder.length-1);
    }*/


    // 二叉树创建字符串
    public void treeToString(TreeNode t, StringBuilder sb) {
        if (t == null) {
            return;
        }
        sb.append(t.value);
        if (t.left != null) {
            sb.append("(");
            treeToString(t.left, sb);
            sb.append(")");
        } else {
            //t.left == null
            if (t.right == null) {
                return;
            } else {
                sb.append("()");
            }
        }

        if (t.right == null) {
            return;
        } else {
            sb.append("(");
            treeToString(t.right, sb);
            sb.append(")");
        }
    }

    public String tree2str(TreeNode root) {
        if (root == null) {
            return null;
        }
        StringBuilder sb = new StringBuilder();
        treeToString(root, sb);
        return sb.toString();
    }


    //前序遍历非递归写法
    public List<Character> preorderTraversal(TreeNode root) {
        List<Character> ret = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        while (cur != null || !stack.isEmpty()) {
            while (cur != null) {
                stack.push(cur);
                ret.add(cur.value);
                cur = cur.left;
            }
            TreeNode top = stack.pop();
            cur = top.right;
        }
        return ret;
    }

    //中序遍历非递归写法
    public List<Character> inorderTraversal(TreeNode root) {
        List<Character> ret = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        while (cur != null || !stack.isEmpty()) {
            while (cur != null) {
                stack.push(cur);
                cur = cur.left;
            }
            TreeNode top = stack.pop();
            ret.add(top.value);
            cur = top.right;
        }
        return ret;
    }

    //后序遍历非递归写法
    public List<Character> postorderTraversal(TreeNode root) {
        List<Character> ret = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        TreeNode prev = null;
        while (cur != null || !stack.isEmpty()) {
            while (cur != null) {
                stack.push(cur);
                cur = cur.left;
            }
            TreeNode top = stack.peek();//注意这里的根一直被存储在top  后面要判断
            if (top.right == null || top.right == prev) {
                stack.pop();
                ret.add(top.value);
                prev = top;
            } else {
                cur = top.right;
            }
        }
        return ret;
    }
}


